package com.woniu.account.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.woniu.account.dto.venueAdmin.VenueAdminDto;
import com.woniu.account.form.venueAdmin.*;
import com.woniu.account.model.VenueAdmin;
import com.woniu.account.model.VenueAdminRole;
import com.woniu.account.param.venueAccount.AddVenueAdminParam;
import com.woniu.account.param.venueAccount.VenueAdminLoadParam;
import com.woniu.account.param.venueAccount.VenueAdminLoginParam;
import com.woniu.account.service.VenueAdminRoleService;
import com.woniu.account.service.VenueAdminService;
import com.woniu.exception.YuJiaException;
import com.woniu.exception.venueAdmin.VenueAdminException;
import com.woniu.exception.venueAdmin.VenueAdminExceptionCode;
import com.woniu.model.Result;
import com.woniu.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 杜岷芫
 * @since 2024年07月11日
 */

@Api(tags = "场馆管理员信息")
@RestController
@RequestMapping("/venueAdmin")
public class VenueAdminController {
    @Autowired
    private VenueAdminService venueAdminService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private MD5Util md5Util;
    @Autowired
    private VenueAdminRoleService venueAdminRoleService;

    @ApiOperation("场馆管理员登录")
    @PostMapping("/login")
    public Result login(@RequestBody VenueAdminLoginFrom from)throws Exception{
        HttpServletResponse response = WebUtil.getResponse();
        VenueAdminDto venueAdminDto=venueAdminService.login(BeanUtil.toBean(from, VenueAdminLoginParam.class));
        HashMap<String, Object> tokenMap = new HashMap<String, Object>();
        tokenMap.put("venueAdmin", venueAdminDto);
        String refreshToken= JwtUtil.createVenueAdminToken(tokenMap,24*60);
        String accessToken= JwtUtil.createVenueAdminToken(tokenMap,30);
        response.setHeader("yujia-token",accessToken);
        response.setHeader("Access-Control-Expose-Headers", "yujia-token");
        //存进redis
        redisUtil.set(accessToken,refreshToken,24*60*60);
        return Result.getResult().setData(venueAdminDto).setMsg("登陆成功");
    }
    @ApiOperation("加载所有场馆管理员")
    @PostMapping("/loadVenueAdmins")
    public Result load(@RequestBody VenueAdminLoadFrom from)throws Exception{
        PageInfo<VenueAdminDto> venueAdminDtoPageInfo=venueAdminService.load(BeanUtil.toBean(from, VenueAdminLoadParam.class));
        return Result.getResult().setData(venueAdminDtoPageInfo).setMsg("查询成功");
    }

    @ApiOperation("修改场馆管理员的状态")
    @GetMapping("/changeState/{venueAdminId}/{state}")
    public Result changeState(@PathVariable(value = "venueAdminId") Integer venueAdminId,@PathVariable("state") Integer state) throws Exception {
        String token = WebUtil.getToken();
        String refreshToken = redisUtil.get(token);
        VenueAdminDto venueAdminDto = JSONUtil.toBean(JSONUtil.toJsonStr(JwtUtil.getVenueAdmin(refreshToken)),VenueAdminDto.class);
        if (venueAdminDto.getVenueAdminId()== venueAdminId) throw new VenueAdminException(VenueAdminExceptionCode.VENUE_ADMIN_CANNOT_CHANGE);
        venueAdminService.changeState(venueAdminId,state);
        return Result.getResult().setMsg("修改状态成功");
    }

    @ApiOperation("删除场馆管理员")
    @GetMapping("/delete/{venueId}")
    public Result delete(@PathVariable(value = "venueId") Integer venueId) throws Exception {
        QueryWrapper<VenueAdmin> qw = new QueryWrapper<VenueAdmin>().eq("venue_id", venueId);
        VenueAdmin one = venueAdminService.getOne(qw);
        venueAdminService.removeById(one);
        QueryWrapper<VenueAdminRole> qw1 = new QueryWrapper<VenueAdminRole>().eq("venue_admin_id", one.getVenueAdminId());
        venueAdminRoleService.remove(qw1);
        return Result.getResult().setMsg("成功");
    }

    @ApiOperation("新增场馆管理员")
    @PostMapping("/addAdminAccount")
    @RequiredRole("管理员")
    public Result addAdminAccount(@RequestBody AddVenueAdminForm form) throws Exception {
        String token = WebUtil.getToken();
        String s = redisUtil.get(token);
        VenueAdminDto venueAdminDto1 = JSONUtil.toBean(JSONUtil.toJsonStr(JwtUtil.getVenueAdmin(s)),VenueAdminDto.class);
        AddVenueAdminParam param = BeanUtil.toBean(form, AddVenueAdminParam.class);
        param.setVenueId(venueAdminDto1.getVenueId());
        VenueAdminDto venueAdminDto= venueAdminService.addVenueAdmin(param);
        return Result.getResult().setData(venueAdminDto).setMsg("新增管理员成功");
    }

    @ApiOperation("新增场馆管理员 for 场馆认证")
    @PostMapping("/addVenueAdmin")
    public Result addVenueAdmin(@RequestBody AddVenueAdminForm form) throws Exception {
        AddVenueAdminParam param = BeanUtil.toBean(form, AddVenueAdminParam.class);
        VenueAdminDto venueAdminDto= venueAdminService.addVenueAdmin(param);
        return Result.getResult().setData(venueAdminDto).setMsg("新增管理员成功");
    }

    @ApiOperation("修改场馆管理员信息")
    @PostMapping("/updateAdmin")
    @RequiredRole("管理员")
    public Result updateAdminAccount(@RequestBody UpdateVenueAdminForm form) throws Exception {
        boolean b = venueAdminService.updateById(BeanUtil.toBean(form, VenueAdmin.class));
        if (!b) throw new VenueAdminException(VenueAdminExceptionCode.VENUE_ADMIN_CHANGE_FAIL);
        VenueAdminDto venueAdminDto = BeanUtil.toBean(venueAdminService.getById(form.getVenueAdminId()), VenueAdminDto.class);
        return Result.getResult().setData(venueAdminDto).setMsg("修改成功");
    }


    @ApiOperation("加载管理员自己的信息")
    @PostMapping("/loadAccount")
    public Result loadAccount(@RequestHeader("token") String token) throws Exception {
        String s = redisUtil.get(token);
        VenueAdminDto venueAdminDto = JSONUtil.toBean(JSONUtil.toJsonStr(JwtUtil.getVenueAdmin(s)),VenueAdminDto.class);
        VenueAdmin venueAdmin = venueAdminService.getById(venueAdminDto.getVenueAdminId());
        if (ObjectUtil.isEmpty(venueAdmin)) throw new VenueAdminException(VenueAdminExceptionCode.VENUE_ADMIN_NOT_LOGIN);
        VenueAdminDto accountLoginDto = BeanUtil.toBean(venueAdmin, VenueAdminDto.class);
        return Result.getResult().setData(accountLoginDto).setMsg("查询成功");
    }

    /**
     * 发送修改密码的验证码
     * @param form
     * @return
     * @throws Exception
     */

    @ApiOperation("修改密码")
    @PostMapping("/updateAdminPass")
    public Result updateAdminPass(@RequestBody UpdateVenueAdminPassForm form) throws Exception {
        String token = WebUtil.getResponse().getHeader("token");
        String s = redisUtil.get(token);
        VenueAdminDto venueAdminDto = (VenueAdminDto) JwtUtil.getVenueAdmin(s);
        VenueAdmin account = venueAdminService.getById(venueAdminDto.getVenueAdminId());
        if (ObjectUtil.isEmpty(account)) throw new VenueAdminException(VenueAdminExceptionCode.VENUE_ADMIN_NOT_LOGIN);
        String s1 = redisUtil.get(RedisKeyUtil.registerCodeKey(account.getVenueAdminPhone()));
        if(!s1.equals(form.getCode())) throw new VenueAdminException(500,"验证码错误");
        String newPwd = md5Util.encryption(account.getVenueAdminPhone(), form.getAdminPass());
        if (newPwd.equals(account.getVenueAdminPassword())) throw new VenueAdminException(500,"新旧密码不能一致");
        account.setVenueAdminPassword(newPwd);
        boolean b = venueAdminService.updateById(account);
        if (!b) throw new VenueAdminException(VenueAdminExceptionCode.VENUE_ADMIN_CHANGE_FAIL);
        return Result.getResult().setMsg("修改成功");
    }

    @ApiOperation("加载教练")
    @GetMapping("/loadCoach/{venueId}/{roleId}")
    public Result<List<VenueAdminDto>> loadCoach(@PathVariable("venueId") Integer venueId,@PathVariable("roleId") Integer roleId) throws Exception {
        List<VenueAdminDto>  venueAdminDtos = venueAdminService.getVenueCoachsById(roleId,venueId);
        return Result.getListResult(VenueAdminDto.class).setData(venueAdminDtos).setMsg("查询成功");
    }

    @ApiOperation("通过id查找场馆教练")
    @GetMapping("/byId/{id}")
    public Result getVenueCoachBtId(@PathVariable("id") Integer id) {
        VenueAdmin byId = venueAdminService.getById(id);
        VenueAdminDto venueAdminDto = BeanUtil.toBean(byId, VenueAdminDto.class);
        return Result.getResult().setData(venueAdminDto).setMsg("成功");
    }

    @ApiOperation("通过ids查找场馆教练")
    @PostMapping("/byIds")
    public Result getVenueCoachBtIds(@RequestBody GetVenueCoachFrom from) {
//    public Result<List<VenueAdminDto>> getVenueCoachBtIds(@PathVariable("ids") Set<Integer> ids) {
        List<VenueAdminDto> byIds = venueAdminService.getByIds(from.getIds());
        return Result.getResult().setData(byIds).setMsg("成功");
//        return Result.getListResult(VenueAdminDto.class).setData(byIds).setMsg("成功");
    }

}

